var db = require('./../../conn/db');
var $sql = require('./../../conn/sqlstr');
var md5 = require('md5-node');
// npm i -S time-formater
var dtime = require('time-formater');


class Admin {
	showLogin(req, res, next) {
		res.render('admin/login.html');
	};
	logout(req, res, next){
		req.session.adminInfo = null; // 删除session
		res.redirect('/admin/login');
	};
	/**
	 * 后台登录
	 */
	admin_login(req, res, next) {
		const getIp = req.headers['x-real-ip'] ? req.headers['x-real-ip'] : req.ip.replace(/::ffff:/, '');
		let params = req.body;
		db.query($sql.admin.login, [md5(params.pass), params.ccount], (err,result) => {
			if(err) {
				return res.status(500).send('Server error.');
      }
			if(!result[0]){
				res.json({code: 1, msg: '账号或密码错误'});
			} else {
				if(result[0].is_open == 1){
					db.query($sql.admin.update_ip, [getIp, result[0].id], (e,r) => {})
					req.session.adminInfo = JSON.stringify(result[0])
					res.json({code: 0, msg: '登录成功'});
				} else {
					res.json({code: 2, msg: '该账号被停用了'});
				}
			}
		})
	};

	/**
	 * 后台主页
	 */
	showMain(req, res, next) {
		let adminInfo = JSON.parse(req.session.adminInfo)
		res.render('admin/index.html', adminInfo);
	};
	showHome(req, res, next) {
		db.query($sql.ccount.sql, (err, result) => {
			if(err) {
				return res.status(500).send('Server error');
			}
			let d = result;
			let adminInfo = JSON.parse(req.session.adminInfo);
			let params = {
				admin: adminInfo.name,
				ip: adminInfo.ip,
				users_num: d[0].num,
				comment_num: d[1].num,
				message_num: d[2].num,
				dot_num: d[3].num
			}
			res.render('admin/home.html', params);
		})
	};

	/**
	 * 获取用户列表
	 */
	showUser(req, res, next) {
		let page =  parseInt(req.params.page) || 1;
		let num = 30;
		let last_page = page - 1;
		db.query($sql.user.find, [num, last_page * num], (err, result) => {
			if (err) {
				return res.status(500).send('Server error');
			}
			res.render('admin/user.html', {
				userList: result,
				index: result[0] ? result[0].count : 0,
				all_page: result[0] ? Math.ceil(result[0].count / num) : 0,
				current_page: req.params.page ? page : 1
			});
		})
	};
  
	showAddUser(req, res, next) {
		res.render('admin/add_user.html');
	};
	showUpdateUser(req, res, next) {
		let id = req.params.id;
		db.query($sql.user.get_user, [id], (err, result) => {
			if (err) {
				return res.status(500).send('Server error');
			}
			res.render('admin/update_user.html', result[0]);
		})
	};
	/**
	 * 添加用户
	 */
	addUser(req, res) {
		let date = dtime().format('YYYY-MM-DD HH:mm:ss');
		let d = req.body;
		db.query($sql.user.add, [d.ccount,d.u_name, md5(d.pass), d.sex, date, md5(d.ccount)], (err, result) => {
			if (err) {
				return res.status(500).send('Server error');
			}
			res.json({code: 0, msg: '用户添加成功！'});
		})
	}
	// 检查用户名是否存在
	verifyName(req,res, next) {
		db.query($sql.user.verify_name, [req.body.ccount], (err,result) => {
			if (err) {
				return res.status(500).send('Server error');
			}
			if(result.length > 0) {
				res.json({code: 2, msg: '该账号已存在！请重新输入'})
			} else {
				next();
			}
		})
	}

	/**
	 * 更新用户
	 */
	updateUser(req, res, next) {
		let d = req.body;
		if(d.pass) {
			db.query($sql.user.update, [d.u_name, md5(d.pass), d.sex, d.id, d.ccount], (err, result) => {
				if(err){
					return res.status(500).send('Server error');
				}
				res.json({code: 0, msg: '修改成功！'});
			});
		}else {
			db.query($sql.user.update1, [d.u_name, d.sex, d.id, d.ccount], (err, result) => {
				if(err){
					return res.status(500).send('Server error');
				}
				res.json({code: 0, msg: '修改成功！'});
			});
		}
	}

	/**
	 * 删除用户
	 */
	delUser(req,res,next) {
		let d = req.body;
		db.query($sql.user.remove, [d.id], (err, result) => {
			console.log('删除用户：' + JSON.stringify(result[0]))
			if(err) {
				return res.status(500).send('Sever error');
			}
			res.json({code: 0, msg: '删除成功！'});
		})
	}

	/**
	 * 批量删除用户
	 */
	delMoreUser(req, res, next) {
		let d = req.body.data;
		let sqltr = `
			DELETE users,message,comments,dot
			FROM users 
			LEFT JOIN message ON users.id=message.u_id
			LEFT JOIN comments ON message.id=comments.m_id
			LEFT JOIN dot ON message.id=dot.m_id
			WHERE users.id in (${d})
		`
		db.query(sqltr, (err, result) => {
			console.log('批量删除结果：' + JSON.stringify(result));
			if(err) {
				return res.status(500).send('Server error')
			}
			res.json({code: 0, msg: '删除成功！'})
		})
	}
	/**
	 * 用户搜索
	 */
	searchUser(req, res, next) {
		if(req.body.ccount){
			db.query($sql.user.search, [req.body.ccount], (err,result) => {
				if (err) {
					return res.status(500).send('Server error');
				}
				res.render('admin/user.html', {
					userList: result
				});
			})
		} else {
			res.redirect('/admin/user');
		}
	}

	/**
	 * 获取管理员列表
	 */
	showAdmin(req, res, next) {
		db.query($sql.admin.list, (err, result) => {
			if (err) {
				return res.status(500).send('Server error');
			}
			res.render('admin/admin_list.html', {
				adminList: result
			});
		})
	}

	/**
	 * 验证是否是超级管理员
	 */
	superAdmin(req, res, next) {
		let status = JSON.parse(req.session.adminInfo).status;
		if (status != 1) {
			res.json({code: 2, msg: '只有超级管理员才有该权限'});
		} else {
			next();
		}
	}
	/**
	 * 启动或者禁用管理员
	 */
	openAdmin(req, res, next) {
		let d = req.body;
		db.query($sql.admin.open_admin, [d.is_open, d.id], (err, result) => {
			console.log('设置管理员权限结果：' + JSON.stringify(result));
			if(err){
				return res.status(500).send('Server error')
			}
			res.json({code: 0, msg: '设置成功！'});
		})
	}
	/**
	 * 删除管理员
	 */
	delAdmin(req, res) {
		let d = req.body;
		db.query($sql.admin.remove, [d.id], (err, result) => {
			if(err) {
				return res.status(500).send('Server error');
			}
			res.json({code: 0, msg: '删除成功！'});
		})
	}

	/**
	 * 添加管理员
	 */
	addAdmin(req, res) {
		let d = req.body;
		let date = dtime().format('YYYY-MM-DD HH:mm:ss');
		db.query($sql.admin.add, [d.name, md5(d.pass), d.is_open, 2, date], (err, result) => {
			if(err) {
				return res.status(500).send('Server error');
			}
			res.json({code: 0, msg: '管理员添加成功！'});
		});
	}
	showAddAdmin(req, res) {
		res.render('admin/add_admin.html');
	}

	/**
	 * 更新管理员信息
	 */
	updateAdmin(req, res) {
		let d = req.body;
		if(d.pass) {
			db.query($sql.admin.update, [d.name, md5(d.pass), d.is_open, d.id], (err, result) => {
				if(err){
					return res.status(500).send('Server error');
				}
				res.json({code: 0, msg: '修改成功！'});
			});
		}else {
			db.query($sql.admin.update1, [d.name, d.is_open, d.id], (err, result) => {
				if(err){
					return res.status(500).send('Server error');
				}
				res.json({code: 0, msg: '修改成功！'});
			});
		}
	}
	showUpdateAdmin(req, res) {
		let id = req.params.id;
		db.query($sql.admin.get_admin, [id], (err, result) => {
			if (err) {
				return res.status(500).send('Server error');
			}
			res.render('admin/update_admin.html', result[0]);
		})
	}
	/**
	 * 渲染留言管理页面
	 */
	showMessage(req, res) {
		let page =  parseInt(req.params.page) || 1;
		let num = 30;
		let last_page = page - 1;
		db.query($sql.message.find, [num, last_page * num], (err, result) => {
			if (err) {
				return res.status(500).send('Server error');
			}
			res.render('admin/messages.html', {
				messageList: result,
				index: result[0] ? result[0].count : 0,
				all_page: result[0] ? Math.ceil(result[0].count / num) : 0,
				current_page: req.params.page ? page : 1
			});
		})
	}
	/**
	 * 删除留言记录
	 */
	delMessage(req, res) {
		let id = req.body.id;
		db.query($sql.message.remove, [id], (err, result) => {
			console.log('删除留言结果：'+ JSON.stringify(result));
			if(err){
				return res.status(500).send('Server error');
			}
			res.json({code: 0, msg: '删除成功！'});
		});
	}
	/**
	 * 	批量删除留言 
	 */
	delMoreMessage(req, res) {
		let d = req.body.data;
		let sqltr = `
			DELETE message,comments,dot 
			FROM message 
			LEFT JOIN comments ON message.id=comments.m_id 
			LEFT JOIN dot ON message.id=dot.m_id 
			WHERE message.id in (${d})
		`
		db.query(sqltr, (err, result) => {
			console.log('批量删除结果：' + JSON.stringify(result));
			if(err) {
				return res.status(500).send('Server error')
			}
			res.json({code: 0, msg: '删除成功！'})
		})
	}

	/**
	 * 搜索留言 
	 */
	searchMess(req, res) {
		if(req.body.ccount){
			db.query($sql.message.search, [req.body.ccount], (err, result) => {
				if (err) {
					return res.status(500).send('Server error');
				}
				res.render('admin/messages.html', {
					messageList: result
				});
			});
		} else {
			res.redirect('/admin/message');
		}
	}

	/**
	 * 渲染评论管理页面
	 */
	showComment(req, res) {
		let page =  parseInt(req.params.page) || 1;
		let num = 30;
		let last_page = page - 1;
		db.query($sql.comments.find, [num, last_page * num], (err, result) => {
			if (err) {
				return res.status(500).send('Server error');
			}
			res.render('admin/comment.html', {
				commentList: result,
				index: result[0] ? result[0].count : 0,
				all_page: result[0] ? Math.ceil(result[0].count / num) : 0,
				current_page: req.params.page ? page : 1
				// console.log(result[0].add_time.toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, ''));
			});
		})
	}

	/**
	 * 删除评论 
	 */
	delComment(req, res) {
		db.query($sql.comments.remove, [req.body.id], (err, result) => {
			if(err) {
				return res.status(500).send('Server error');
			}
			res.json({code: 0, msg: '删除成功！'});
		});
	}

	/**
	 * 批量删除评论 
	 */
	delMoreComment(req, res) {
		let d = req.body.data;
		let sqltr = `DELETE FROM comments WHERE id in (${d})`
		db.query(sqltr, (err, result) => {
			console.log('批量删除评论结果：' + JSON.stringify(result));
			if(err) {
				return res.status(500).send('Server error')
			}
			res.json({code: 0, msg: '删除成功！'})
		})
	}
	/**
	 * 搜索评论
	 */
	searchComment(req, res){
		console.log('搜索评论id: ' + req.body.ccount);
		if(req.body.ccount){
			db.query($sql.comments.search, [req.body.ccount], (err, result) => {
				if (err) {
					return res.status(500).send('Server error');
				}
				res.render('admin/comment.html', {
					commentList: result
				});
			});
		} else {
			res.redirect('/admin/comment');
		}	
	}
}


module.exports = new Admin();
